from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Order
from apps.member.models import MemberPoints
from apps.delivery.models import Delivery

@receiver(post_save, sender=Order)
def handle_order_status_change(sender, instance, created, **kwargs):
    if created:
        return

    # 当订单完成时，更新会员积分
    if instance.status == 'completed':
        points = int(instance.total_amount)  # 简单地用订单金额作为积分
        member_points, _ = MemberPoints.objects.get_or_create(user=instance.user)
        member_points.points += points
        member_points.save()

    # 当订单支付成功时，创建配送记录
    if instance.status == 'paid':
        # 这里可以添加配送员分配逻辑
        available_staff = DeliveryStaff.objects.filter(is_active=True).first()
        if available_staff:
            Delivery.objects.create(
                order=instance,
                staff=available_staff,
                status='assigned'
            ) 